<?php

namespace tmcore\services\crud\generators;

use tmcore\services\crud\enum\TplEnum;
use tmcore\services\crud\UtilService;

class VueApi extends Generate
{

    /**
     * @var string
     */
    protected string $fileType = 'ts';

    /**
     * 替换变量
     */
    public function replaceContent()
    {
        $search = [
            '{CONTENT_JS}',
        ];

        $replace = [
            $this->getVueApiContent(),
        ];

        $content = UtilService::replaceFileContent($search, $replace, $this->getStub('api'));

        $this->setContent($content);
    }

    /**
     * 返回模板路径
     * @param string $type
     * @return mixed|string|string[]
     */
    public function getStub(string $type = 'api')
    {
        $basePath = 'vue/api/';

        $stubs = [
            'lists' => $this->getTplPath($basePath . 'lists'),
            'add' => $this->getTplPath($basePath . 'add'),
            'edit' => $this->getTplPath($basePath . 'edit'),
            'delete' => $this->getTplPath($basePath . 'delete'),
            'detail' => $this->getTplPath($basePath . 'detail'),
            'export' => $this->getTplPath($basePath . 'export'),
            'import' => $this->getTplPath($basePath . 'import'),
            'treeAll' => $this->getTplPath($basePath . 'treeAll'),
            'api' => $this->getTplPath($basePath . 'api'),
        ];

        return $type ? $stubs[$type] : $stubs;
    }

    /**
     * 设置文件路径
     */
    public function setFilePath()
    {
        $name = UtilService::lcfirst($this->getCamelClassName()) . '.' . $this->fileType;
        $this->setCrudFileName($name);

        $module_path = dirname($this->rootPath) . '/admin/src/api/';
        if (!empty($this->classDir)) $module_path .= $this->classDir . '/';
        $this->setCrudModuleFilePath($module_path);

        $data_path = $this->crudDir . 'vue/src/api/';
        if (!empty($this->classDir)) $data_path .= $this->classDir . '/';
        $this->setCrudDataFilePath($data_path);
    }

    /**
     * 获取vueApi内容
     * @return string|string[]
     */
    public function getVueApiContent() {

        $search = [
            '{TABLE_COMMENT}',
            '{CAMEL_CLASS_NAME}',
            '{ROUTE}'
        ];

        $replace = [
            $this->crudData['table_comment'],
            UtilService::lcfirst($this->crudData['class_name']),
            UtilService::lower($this->classDir) . ($this->classDir ? '/' : '') . UtilService::lcfirst($this->crudData['class_name'])
        ];

        return UtilService::replaceFileContent($search, $replace, $this->getStubContent(TplEnum::getVueApiTpl($this->crudData)), false);
    }
}